//
//  PostSender.m
//  KOP
//
//  Created by 王贵源 on 15/9/23.
//  Copyright © 2015年 王贵源. All rights reserved.
//

#import "FilePostSender.h"
//#import "AFNetworkActivityIndicatorManager.h"
//#import "AFNetworkReachabilityManager.h"

@interface FilePostSender()<NSURLConnectionDelegate>

@end
@implementation FilePostSender
- (void)sendTo:(NSString *)url data:(NSMutableDictionary *)paras fileData:(NSMutableDictionary *)fileData header:(NSMutableDictionary *)header{
    
    /***
     
     1.创建一个 Request
     
     2.拼装请求数据
     
     3.发送请求并带回数据 1.header 2.body
     
     
     
     header 处理
     
     遍历 header 调 request 的 setValue 方法
     
     
     paras 处理
     
     1.遍历 paras
     2.判断每一个值是不是 nsdata 或者 nsdata数组
     
     a. 如果是文件
     
     按照文件的拼装形式进行 body 的拼装
     
     b. 如果不是文件 按照普通参数处理
     
     
     */
    
    NSString *TWITTERFON_FORM_BOUNDARY = @"---------------------------JHMLY622510";
    
    //根据url初始化request
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                        timeoutInterval:10];
    
    
    //分界线
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    
    //结束符
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //body 数据
    NSMutableData *myRequestData=[NSMutableData data];
    //参数的集合的所有key的集合
    NSArray *keys= [paras allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)//普通参数
    {
        NSString *key=[keys objectAtIndex:i];
        //添加分界线，换行
        [myRequestData appendData:[[NSString stringWithFormat:@"%@\r\n",MPboundary] dataUsingEncoding:NSUTF8StringEncoding ]];
        //添加字段名称，换2行
        [myRequestData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding] ];
        //添加字段的值
        NSString *_value = [paras objectForKey:key];
        NSString * xxx = [NSString stringWithFormat:@"%@",_value];
        
        
        [myRequestData appendData:[xxx dataUsingEncoding:NSUTF8StringEncoding]];
        [myRequestData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    NSLog(@"%@",[[NSString alloc] initWithData:myRequestData encoding:NSUTF8StringEncoding]);
    
    NSArray *fileKeys= [fileData allKeys];
    
    if ( fileData  && [fileData count] > 0) {
        for(int i=0;i<[fileKeys count];i++)//文件参数
        {
            NSString *key=[fileKeys objectAtIndex:i];
            id  value = [fileData objectForKey:key];
            
            if ([value isKindOfClass:[NSString class]]) {
                /////添加分界线，换行
                [myRequestData appendData:[[NSString stringWithFormat:@"%@\r\n",MPboundary] dataUsingEncoding:NSUTF8StringEncoding]];
                //声明pic字段，文件名为boris.png,key
                [myRequestData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",key,value] dataUsingEncoding:NSUTF8StringEncoding]];
                //声明上传文件的格式
                [myRequestData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding ]];
                
                NSData * data = [NSData dataWithContentsOfFile:value];
                
                [myRequestData appendData:data];
                
                NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
                
                [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
                
            }else{
                
                NSArray * files = value;
                for(int i=0;i<[files count];i++){
                    NSString *file=[files objectAtIndex:i];
                    
                    /////添加分界线，换行
                    [myRequestData appendData:[[NSString stringWithFormat:@"%@\r\n",MPboundary] dataUsingEncoding:NSUTF8StringEncoding]];
                    //声明pic字段，文件名为boris.png,key
                    [myRequestData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",key,file] dataUsingEncoding:NSUTF8StringEncoding]];
                    //声明上传文件的格式
                    [myRequestData appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding ]];
                    
                    NSData * data = [NSData dataWithContentsOfFile:file];
                    
                    [myRequestData appendData:data];
                    
                    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
                    
                    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
                }
            }
        }
    }
    //处理 header
    if (header) {
        NSArray * headerKeys = [header allKeys];
        for(int i=0;i<[headerKeys count];i++){
            NSString *key=[headerKeys objectAtIndex:i];
            [request setValue:[header objectForKey:key] forHTTPHeaderField:key];
        }
    }
    
    //发送请求
    if (fileData) {
        [request setValue:[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY] forHTTPHeaderField:@"Content-Type"];
    }else{
        [request setValue:[[NSString alloc]initWithFormat:@"application/x-www-form-urlencoded;charset=utf-8  boundary=%@",TWITTERFON_FORM_BOUNDARY] forHTTPHeaderField:@"Content-Type"];
    }
    [request setHTTPBody:myRequestData];
    
    //    NSHTTPURLResponse *response = nil;
    [request setHTTPMethod:@"POST"];
    //    NSError *error = nil;
    //    NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //
    //    NSString *resultStr = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
    //
    //    NSMutableDictionary * target = [[NSMutableDictionary alloc] init];
    //
    //
    //    //组装返回
    //    if (response) {
    //        [target setValue:[response allHeaderFields] forKey:@"headers"];
    //    }
    //    if (error) {
    //        [target setValue:error forKey:@"error"];
    //    }
    //
    //    [target setValue:resultStr forKey:@"result"];
    //
    //
    //    return target;
    
    
    
//    AFNetworkReachabilityManager *reachManager =
//    [AFNetworkReachabilityManager sharedManager];
//    // 2.设置网络状态改变后的处理
//    [reachManager startMonitoring];
//    FIXME  提示网络状态
//    [reachManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        // 当网络状态改变了, 就会调用这个block
//        switch (status) {
//            case AFNetworkReachabilityStatusUnknown: // 未知网络
//                NSLog(@"未知网络");
//                break;
//                
//            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
//                NSLog(@"没有网络(断网)");
//                break;
//                
//            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
//            {NSLog(@"手机自带网络");
//                //链接服务器
//                NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//                NSLog(@"手机网络链接服务器 == %@",connection);
//            } break;
//                
//            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
//            {
//                NSLog(@"WIFI");
//                //链接服务器
//                NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//                NSLog(@"WIFI链接服务器 == %@",connection);
//            }break;
//        }
//    }];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    NSLog(@"WIFI链接服务器 == %@",connection);

}
//接收到服务器回应的时候调用此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *res = (NSHTTPURLResponse*)response;
    _receiveData = [NSMutableData data];//数据存储对象的的初始化
    _dataPackSerialNo=0;
    NSLog(@"收到服务器回应 ＝＝ %@",[res allHeaderFields]);
    [self.resultDic setValue:[res allHeaderFields] forKey:@"headers"];
    
}
//接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_receiveData appendData:data];
    NSLog(@"收到服务器传回的数据包，数据包序号：%d",self.dataPackSerialNo);
    _dataPackSerialNo += 1;
}
//数据传输完之后调用此方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"数据传输完成，输出所有数据结果。。。");
    NSString *receiverStr = [[NSString alloc]initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",receiverStr);
    [self.resultDic setValue:receiverStr forKey:@"result"];
    //发送数据
    [self.filepostDelegate filesendresultDic:self.resultDic];
    
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"网络请求出错：%@",error);
    [self.resultDic setValue:error forKey:@"error"];
}
- (NSMutableDictionary *)resultDic{
    if (!_resultDic) {
        _resultDic = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return _resultDic;
    
}
@end
